﻿using System.Collections.Generic;
using System.IO;
using System.Xml;
using Crap4Net;
using NUnit.Framework;
using System;

namespace Crap4Net.UnitTests.FormatterTests
{
    [TestFixture]
    public class XmlFormatterTest
    {
        readonly static MethodSignature _ctor = new MethodSignature("dll", "namespace", "Class1", ".ctor", new string[] {"int" });
        readonly static MethodSignature _method1 = new MethodSignature("dll", "namespace", "Class1", "method1", new string[] {"int","float" });
        readonly static MethodSignature _method2 = new MethodSignature("dll", "namespace", "Class2", "method2", new string[] { });

        private readonly IList<CombinedDataEntry> _Data =
            new List<CombinedDataEntry> { new CombinedDataEntry(_ctor,100,5),  
                                        new CombinedDataEntry(_method1, 0, 3), 
                                        new CombinedDataEntry(_method2, 50, 2) };

        [Test]
        public void FormatReport_GivenValidData_BuildProperXml()
        {
            var xmlDoc = new XmlFormatter().FormatReport(_Data);

            string actual = GetStringfromXml(xmlDoc);
            string expected = LoadXml(@"UnitTestData\CrapReport.xml");
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void FormatAndSaveToFile_ValidData_SavesAsXMlToGivenFileName()
        {
            try
            {
                new XmlFormatter().FormatAndSaveToFile(_Data, "output.xml");

                string actual = LoadXml("output.xml");
                string expected = LoadXml(@"UnitTestData\CrapReport.xml");
                Assert.AreEqual(expected, actual);
            }
            finally
            {
                File.Delete("output.xml");
            }


        }

        private static string GetStringfromXml(XmlDocument xmlDoc)
        {
            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = new XmlTextWriter(stringWriter))
                {
                    xmlDoc.WriteTo(xmlWriter);
                }
                string actual = stringWriter.ToString();
                return actual;
            }
        }
        private static string LoadXml(string fileName)
        {
            var loaded = new XmlDocument();
            loaded.Load(fileName);
            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = new XmlTextWriter(stringWriter))
                {
                    loaded.WriteTo(xmlWriter);
                }
                return stringWriter.ToString();
            }
        }
    }
}
